package com.zsoft.webmail.servlet.hainannet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.zsoft.webmail.*;
import com.zsoft.webmail.message.*;
import  comm.http.upload.*;
import com.zsoft.webmail.Application;
import com.zsoft.webmail.mimeutility.MimeUtility;
import comm.util.Utils;
import com.zsoft.webmail.folder.*;

public class MailDownloadServlet extends HttpServlet {
  //private static final String CONTENT_TYPE = Application.getProperty("ContentType");
  private static final String CONTENT_TYPE = "text/html";
  /**Initialize global variables*/
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
comm.http.Request request1=new comm.http.Request(request,Application.getProperty("defaultInputCharset"));
    MemberAuthorization memberAuthToken=null ;
    HttpSession session=request.getSession();
    Object object = session.getAttribute("authBean");
    if(object==null){
      session.setAttribute("authBean",new com.zsoft.webmail.AuthBean(session.getId(),request.getRemoteAddr()));
      response.sendRedirect( "login.jsp" );
      return;
    }else{
      memberAuthToken = ((AuthBean)object).getMemberAuthToken();
      if(memberAuthToken==null){
        response.sendRedirect( "login.jsp" );
        return;
      }
    }


    SmartUpload mailDownload =new SmartUpload();
    //get parameters
    String boxid=request1.getParameter("boxid");
    String mid=request1.getParameter("mid");
    boxid=comm.util.FileUtils.getFilename(boxid);
    mid=comm.util.FileUtils.getFilename(mid);

    char sep='/';
    String webPath=memberAuthToken.webPath;
    String msgPath;

    //get all relevant paths
    String userPath=memberAuthToken.homePath;
    if ( boxid != null )
    {
            FolderList fl=null;
            try{
            fl=new FolderList(userPath+"/directory.cfg");
            }catch(Exception e){

            }
            msgPath = userPath+sep+fl.getValueById(boxid);
    }
    else
            msgPath = webPath;



	String msgFileName=msgPath+sep+mid;

	//--start to download

	// Initialization
	mailDownload.initialize(super.getServletConfig(),request,response);

	// Download file with a physical path
    try{
        mailDownload.downloadFile(msgFileName,MimeUtility.getContentType(mid+".eml"),mid+".eml");
    }catch(Exception e){}
  }
  /**Process the HTTP Post request*/
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request,response);
  }
  /**Clean up resources*/
  public void destroy() {
  }
}